<template>
    <div>
        <el-form class="" :inline="true" label-width="0" :model="formData" size="default" style="width: 100%">
            <el-form-item>
                <el-button type="primary" size="default" @click="start">刷新</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="default" @click="addList">批量添加</el-button>
            </el-form-item>
        </el-form>
        <el-table class="" :data="tableData" height="80vh" style="width: 100%">
            <el-table-column prop="ID" label="ID" width=""></el-table-column>
            <el-table-column prop="label.name" label="标签名称" width=""></el-table-column>
            <el-table-column prop="questionid" label="题目ID" width=""></el-table-column>
            <el-table-column prop="question.name" label="题目名称" width=""></el-table-column>
            <el-table-column label="删除" width="100">
                <template #default="{ row }">
                    <el-button type="danger" :icon="Delete" @click="del(row)" />
                </template>
            </el-table-column>
        </el-table>
        <el-pagination class="pager" @current-change="handleCurrentChange" :page-size="Number(limit)"
            :page-sizes="pageSizes" @size-change="handleSizeChange" layout="total, sizes ,prev, pager, next"
            :total="totalCount">
        </el-pagination>
        <!-- 批量添加 -->
        <el-dialog width="60%" align-center title="" v-model="dialogVisible" :draggable="true" @close="reset">
            <template #header>
                <span class="icon-text el-dialog__header-title">
                    <el-icon class="text-primary">
                        <Guide />
                    </el-icon>
                    批量添加
                </span>
            </template>
            <el-row :gutter="20">
                <el-button size="default">
                    <a href="https://docs.qq.com/sheet/DRUhpWGRIcVRaVUp0?tab=BB08J2" type="primary"
                        target="_bank">批量导入模板</a>
                </el-button>
                <el-upload class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/" :auto-upload="true"
                    :accept="Sheetjsftstring" :http-request="request" :show-file-list="false">
                    <el-button type="primary" size="default">上传文件</el-button>
                </el-upload>
            </el-row>
            <el-row class="margin-top20">
                <el-col>
                    <el-table :data="tabledata" border style="width: 100%" max-height="70vh">
                        <el-table-column prop="分组ID" label="分组ID"> </el-table-column>
                        <el-table-column prop="题目ID" label="题目ID"> </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <el-row class="margin-top20">
                <el-button type="primary" size="default" @click="add" :disabled="!tabledata.length">导入</el-button>
            </el-row>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, onMounted, ref, watch } from 'vue';
import { useStore } from 'vuex';
import {
    // asyncUpdatequestionblack,
    asyncAddquestionblacklist,
    asyncDDelquestionblack,
    asyncSelectquestionblack,
    Iobj
} from '../../../../api';
import { Storekey } from '../../../../interface';
import Studycodemodel from '../../../../mysql_interface/studycodemodel';
import { findpid } from '../../../../util/code';
import {
    getfiletodata2,
    Sheetjsftstring
} from "../../../../util/excel";

const store = useStore(Storekey)

const emit = defineEmits(['set-refresh']);
const p = defineProps<{ vipLabel: Studycodemodel.ILabel }>();
const vipLabel = computed(() => {
    return p.vipLabel
})
const grouplabel = computed(() => {
    const data = store.state.label?.rows.filter((e) => e.type === "题目标签");
    return findpid(data ? data : []);
});

onMounted(() => {
    start()
    emit('set-refresh', start);
})

const formData = ref<Iobj<Studycodemodel.Iquestionblack>>({})
const limit = ref(20);
const pageSizes: number[] = [limit.value, 50, 100, 200,]
const offset = ref(0);
const tableData = ref<Studycodemodel.Iquestionblack[]>([])
const totalCount = ref(0)
const query = computed(() => {
    let _like: [keyof Studycodemodel.Iquestionblack, string | number] | undefined;
    const obj: Iobj<Studycodemodel.Iquestionblack> = {
        labelid: vipLabel.value.ID,
        _order: ["ID"],
        _sortable: "ASC",
        _limit: Number(limit.value),
        _offset: Number(offset.value),
    };
    obj._like = _like;
    return obj;
});
watch(query, v => { start() })
async function start() {
    const { count, rows } = await asyncSelectquestionblack(query.value) // admin 接口
    tableData.value = rows
    totalCount.value = count
}
function handleCurrentChange(val: number) {
    offset.value = limit.value * (val - 1);
    start()
}
const handleSizeChange = (val: number) => {
    limit.value = val
    start()
}

async function del(row: Studycodemodel.Iquestionblack) {
    ElMessageBox.confirm("确定要删除此题目", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(async () => {
            try {
                await asyncDDelquestionblack({ ID: row?.ID });
                ElMessage({ message: "删除成功", type: "success", });
                start()
            } catch (e) {
                ElMessage({ message: String(e), type: "error", });
            }
        })
        .catch(() => {
            ElMessage({ type: "info", message: "已取消", });
        });
}

// 批量添加
const dialogVisible = ref(false)
function addList() {
    dialogVisible.value = true
}

const data = ref<string[][]>([]);
async function request({ file }: { file: File }) {
    data.value = await getfiletodata2<string>(file, 3);
    return true;
}
const tabledata = computed(() => {
    return data.value.map((e) => {
        const [分组ID, 题目ID] = e;
        return {
            分组ID: 分组ID ? String(分组ID).trim() : null,
            题目ID: 题目ID ? String(题目ID).trim() : null,
        };
    });
});
function reset() {
    data.value = [];
}

async function add() {
    const data = tabledata.value.map((e) => {
        return {
            questionid: e?.题目ID,
            labelid: e?.分组ID,
        }
    })
    console.log(tabledata.value, data)
    try {
        await asyncAddquestionblacklist(data)
        ElMessage({ message: "添加成功", type: "success", });
        start()
        dialogVisible.value = false
    } catch (error) {
        console.error("asyncAddquestionblacklist=>", error)
    }
}
</script>

<style scoped></style>